package com.appspot.diasporajava.federation;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.appspot.diasporajava.controller.MainController;
import com.appspot.diasporajava.util.WebsiteVisitor;
import com.appspot.diasporajava.util.XStreamGae;
import com.thoughtworks.xstream.XStream;

@Component
public class WebFinger {
	private static Log log = LogFactory.getLog(WebFinger.class);

	public final static String DESCRIPTOR_CONTEXT = ".well-known/host-meta";
	
	@Autowired
	WebsiteVisitor websiteVisitor;

	public String getTemplate(String hostUri) throws IOException {
		Document doc = Jsoup.connect(hostUri + DESCRIPTOR_CONTEXT).get();
		//String document = websiteVisitor.visit(hostUri + DESCRIPTOR_CONTEXT) ;
		//Document doc = new Document(document);
		log.debug(doc.html());
		Elements elements = doc.select("link");
		return elements.get(0).attr("template");
	}

	public WebFingerVO getUserDescription(String userName, String template)
			throws IOException, JAXBException {
		userName = userName.replaceAll("\\@", "%40");
		String userUrl = template.replaceAll("\\{uri\\}", userName);
		InputStream is = getInputStream(userUrl);
		return unmarshall(is);
	}
	
	public WebFingerVO unmarshall(InputStream inputStream) throws JAXBException, IOException {
		
		XStream stream = new XStream();
		stream.processAnnotations(WebFingerVO.class);
		return (WebFingerVO)stream.fromXML(inputStream);
	}
	
	public WebFingerVO unmarshall(String string) throws JAXBException, IOException {
		
		XStream stream = new XStreamGae();
		stream.processAnnotations(WebFingerVO.class);
		return (WebFingerVO)stream.fromXML(string);
	}	

	public InputStream getInputStream(String urlToRead) throws IOException {
		URL url;
		HttpURLConnection conn;
		url = new URL(urlToRead);
		conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		return conn.getInputStream();

	}

}
